package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
////补货工单完成后修改售货机状态

@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class SupplyTaskCompletedMsgHandler implements MsgHandler {

    @Autowired
    private ChannelService channelService;

    @Autowired
    private VendingMachineService  vendingMachineService;

    @Override
    public void process(String jsonMsg) throws IOException {

        //解析数据
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        if(supplyContract==null || supplyContract.getInnerCode()==""){
            return;
        }
        String   InnerCode     =  supplyContract.getInnerCode();
        List<ChannelEntity> channeles = channelService.getChannelesByInnerCode(InnerCode);
        List<SupplyChannel> supplyDatas = supplyContract.getSupplyData();
        //更新最后补货时间
        UpdateWrapper<VendingMachineEntity> uw = new UpdateWrapper<>();
        uw.lambda().eq(VendingMachineEntity::getInnerCode,supplyContract.getInnerCode()).set(VendingMachineEntity::getLastSupplyTime, LocalDateTime.now());
             vendingMachineService.update(uw);
             supplyDatas.forEach(s->{
                 Optional<ChannelEntity> item = channeles.stream().filter(c -> c.getChannelCode().equals(s.getChannelId())).findFirst();
             if(item.isPresent()){
                 ChannelEntity channel = item.get();
                 channel.setCurrentCapacity(channel.getCurrentCapacity()+s.getCapacity());
                 //更新货道补货时间
                 channel.setLastSupplyTime(LocalDateTime.now());
                 //更新
                 channelService.updateById(channel);
             }
             });

             //更新库存
      /*  for (SupplyChannel supplyData : supplyDatas) {
            String channelId = supplyData.getChannelId();
            for (ChannelEntity channele : channeles) {
                if(channele.getChannelCode().equals(channelId)){
                    var currentCapaCity=channele.getCurrentCapacity()+supplyData.getCapacity();
                    channele.setCurrentCapacity(currentCapaCity);
                    channelService.updateById(channele);
                }
            }
        }*/
    }
}
